import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { Toast } from 'vant';

Vue.use(VueRouter)

const routes = [
  {
    //导航页
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    //登录页
    path: '/login',
    name: 'login',
    //redirect: "/welcome",
    component: () => import('../views/login/LoginView.vue'),
  },
  {
    //用户注册
    path: '/userAdd',
    name: 'userAdd',
    //redirect: "/welcome",
    component: () => import('../views/User/UserAddView.vue'),
  },
  {
    //忘记密码
    path: '/resetting',
    name: 'resetting',
    //redirect: "/welcome",
    component: () => import('../views/User/ResettingView.vue'),
  },
  {
    //我的
    path: '/my',
    name: 'my',
    //redirect: "/welcome",
    component: () => import('../views/User/MyView.vue'),
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/addquestion',
    name: 'addquestion',
    component: () => import('../views/Question/AddQuestion.vue')
  },
  {
    path: '/questionlist',
    name: 'questionlist',
    component: () => import('../views/Question/QuestionList.vue')
  },
  {
    path: '/updatequestion',
    name: 'updatequestion',
    component: () => import('../views/Question/UpdateQuestion.vue')
  }
]

const router = new VueRouter({
  routes
})
//路由守卫
router.beforeEach(async (to, from, next) => {
  // 判断用户是否已经登录
  const token = window.localStorage.getItem("user")
  const outerPaths = ['/login', '/userAdd', '/resetting'];//定义需要排除路由守卫触发时的界面比如登录界面  不排除会出现以下错误Maximum call stack size exceeded
  if (outerPaths.includes(to.path)) {
    next();
  } else {
    if (token == null && !outerPaths.includes(to.path)) {
      Toast({
        message: '请先登录!',
      });
      next("/login");
    } else {
      next();
    }
  }
});

export default router
